# @time     :2022/1/20
# @Author   :Simple
# @FileName :logging
import logging
import logging.handlers
import os
import time

from config import RUN_LOG, log_level


def log_init():
    # 设置格式
    log_format_str = '%(asctime)s %(filename)s[line:%(lineno)d]:%(funcName)s %(levelname)s %(message)s'
    formatter = logging.Formatter(log_format_str)
    # 设置文件句柄
    now_time = time.strftime("%Y_%m_%d_%H_%M_%S")
    log_file_name = now_time + ".log"
    log_file = os.path.join(RUN_LOG, log_file_name)
    dir_path = os.path.dirname(log_file)
    try:
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
    except Exception:
        pass

    file_handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=20 * 1024 * 1024, backupCount=10,
                                                        encoding='utf-8')
    file_handler.setFormatter(formatter)
    # 设置输出流句柄
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)

    # 根据log标识获取log
    root = logging.getLogger("my_log")
    # 设置日志等级
    root.setLevel(log_level)
    # 加入句柄
    root.addHandler(file_handler)
    root.addHandler(stream_handler)
    return root


def get_logger():
    logger = log_init()
    return logger


log = get_logger()

# if __name__ == "__main__":
#     log = get_logger()
#     log.info("测试")
